package jumpInstructions;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import main.IMIPSInstruction;
import main.MIPSSimulator;

public abstract class MIPSJumpInstruction implements IMIPSInstruction {
	public String myRegisterOne;
	public String myRegisterTwo;
	public String myImmediateValue;
	public String myName;
	public String myLabelName;
	public int myTarget;
	protected static Properties myRecognizedRegisters = new Properties();

	public MIPSJumpInstruction() {
	}

	public MIPSJumpInstruction(String input) throws FileNotFoundException,
			IOException {
		myRecognizedRegisters.load(new FileInputStream(new File(
				"recognizedRegisters.properties")));
		myRegisterOne = myRecognizedRegisters.getProperty(input.substring(6,
				11));
		myRecognizedRegisters.load(new FileInputStream(new File(
				"recognizedRegisters.properties")));
		myRegisterTwo = myRecognizedRegisters.getProperty(input.substring(11,
				16));
		String immediateValueString = input.substring(16, 32);

		int temp = Integer.parseInt(immediateValueString, 2);
		byte[] b = new byte[4];
		for (int k = 0; k < 4; k++) {
			int offset = (b.length - 1 - k) * 8;
			b[k] = (byte) ((temp >>> offset) & 0xFF);
		}
		StringBuffer sb = new StringBuffer(b.length * 2);
		char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };
		for (int k = 0; k < b.length; k++) {
			sb.append(hexChar[(b[k] & 0xf0) >>> 4]);
			sb.append(hexChar[b[k] & 0x0f]);
		}
		String hexstring = sb.toString();
		myImmediateValue = "0x" + hexstring.substring(hexstring.length() - 4, hexstring.length());
	}
	
	public String toString(){
		return myName + " " + myRegisterOne +", " + myRegisterTwo + ", " + myImmediateValue;
	}
	
	public void parseImmediate(String inputString){
		if(inputString.substring(16, 17).equals("1")){
			int test = Integer.parseInt(inputString.substring(16, 32), 2);
			test = ~test;
			test++;
			String testString = Integer.toBinaryString(test);
			myTarget = -Integer.parseInt(testString.substring(16, 32), 2);
		} else {
			myTarget = Integer.parseInt(inputString.substring(16, 32), 2);
		}
	}
}
